//
//  GCMEquPlanViewController.m
//  GeeCityManager
//
//  Created by 聚城科技 on 16/5/25.
//  Copyright © 2016年 聚城科技. All rights reserved.
//

#import "GCMEquPlanViewController.h"
#import "GCMScanViewController.h"
#import "GCMUploadViewController.h"
#import "GCMDownLoadViewController.h"
#import "GCMEQUShouYeTableViewCell.h"
#import "GCMEQUShouYeModel.h"
#import "GCMEQUErJiViewController.h"
#import "SubLBXScanViewController.h"
#import "GCMSheBeiRequst.h"
#import "GCMSearchViewController.h"
#import "DBManage.h"
#import "GCMOUTLINECaoZuoModel.h"
#import "LSProgressHUD.h"

@interface GCMEquPlanViewController ()<UITableViewDelegate,UITableViewDataSource>

@end

@implementation GCMEquPlanViewController{

    UIView *_topview;
    UITableView *_tableV;
    NSMutableArray *_dataSource;
    NSMutableArray *_outlinedataSource;
    NSMutableArray *_seachArr;
    UIImageView *navBarHairlineImageView;
    UIButton* rigbutton;
    NSInteger _currentPage;
    UILabel *_nilLabel;
}


-(void)viewWillAppear:(BOOL)animated{

    //去除导航栏下方的横线
    navBarHairlineImageView.hidden = YES;
    rigbutton.hidden = NO;
//    一开始进入页面就把设备的操作类型数据保存下供离线里面的数据使用
    [GCMSheBeiRequst postScanDataSuccess:^(id obj, NSError *err) {
        [[NSUserDefaults standardUserDefaults]setObject:obj forKey:@"shebeiCaoZuoType"];
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self navigationBar];
    [self downLoadData];
    [self createUI];
    [self createTableView];    
    //    下拉刷新
    _tableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _currentPage = 1;
        // 进入刷新状态后会自动调用这个block
        [self downloadTableViewData];
        [_tableV.mj_header endRefreshing];
        
    }];
    //    上拉加载
    _tableV.mj_footer  = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 进入加载状态后会自动调用这个block
        _currentPage ++;
        NSString *pageStr  = [NSString stringWithFormat:@"%ld",_currentPage];
        [self downloadNextPageTableViewDataWith:pageStr];
        [_tableV.mj_footer endRefreshing];
    }];
}

-(void)initData{
    _currentPage = 1;
    _dataSource = [[NSMutableArray alloc]init];
    _outlinedataSource = [[NSMutableArray alloc]init];
}
-(void)downloadTableViewData{
    
    NSLog(@"+++%@",_seachArr);
    
    [GCMSheBeiRequst postSheBeiDataWithaId:_seachArr[0] WithType:_seachArr[1] WithstartDate:_seachArr[2] WithendData:_seachArr[3] WithPage:@"1" Success:^(id obj, NSError *err) {
        [_dataSource removeAllObjects];
        _dataSource = obj;
        [_tableV reloadData];
    }];
}
-(void)downloadNextPageTableViewDataWith:(NSString*)pageStr{
    
    [GCMSheBeiRequst postSheBeiDataWithaId:_seachArr[0] WithType:_seachArr[1] WithstartDate:_seachArr[2] WithendData:_seachArr[3] WithPage:pageStr Success:^(id obj, NSError *err) {
        [_dataSource addObjectsFromArray:obj];
        [_tableV reloadData];
    }];
    
}

-(void)navigationBar{


    navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    self.navigationController.navigationBarHidden = NO;
    rigbutton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 8, 30, 30 )];
    [rigbutton setBackgroundImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [rigbutton addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self.navigationController.navigationBar addSubview:rigbutton];
    
}
-(void)searchButtonClick{

    GCMSearchViewController *seach = [[GCMSearchViewController alloc]init];
    seach.returnArrayBlock = ^(NSArray * arr){
        _seachArr = [NSMutableArray arrayWithArray:arr];
        NSLog(@"返回数据%@",arr);
        [GCMSheBeiRequst postSheBeiDataWithaId:_seachArr[0] WithType:_seachArr[1] WithstartDate:_seachArr[2] WithendData:_seachArr[3] WithPage:@"1" Success:^(id obj, NSError *err) {
            _dataSource  = obj;
            [_tableV reloadData];
            if (_dataSource.count == 0) {
                _nilLabel.hidden = NO;
            }else{
                _nilLabel.hidden = YES;
            }
        }];
    };
    [self.navigationController pushViewController:seach animated:NO];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"返回";
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.backBarButtonItem = backItem;
    

}
-(void)downLoadData{

    //    日期
    NSString *timestr = [NSString stringWithFormat:@"%@",[NSDate date]];
    NSArray *arrayt1 = [timestr componentsSeparatedByString:@" "];
    NSArray *monArr = [arrayt1[0] componentsSeparatedByString:@"-"];
    NSString *nowMon = [NSString stringWithFormat:@"%@-%@-1", monArr[0],monArr[1]];
    NSString *nextMon  = [NSString stringWithFormat:@"%@-%@-1",monArr[0],[NSString stringWithFormat:@"%d",[monArr[1] intValue] +1]];
    _seachArr = [[NSMutableArray alloc]init];
    if ([GCMCZHRequst isExistenceNetwork]) {
        [_seachArr addObject:[GCMUserInfo instance].areaId];
    }else{
        [_seachArr addObject:[[NSUserDefaults standardUserDefaults]valueForKey:@"userInfo"]];
    }
    [_seachArr addObject:@"1"];
    [_seachArr addObject:nowMon];
    [_seachArr addObject:nextMon];
    
    [GCMSheBeiRequst postSheBeiDataWithaId:[GCMUserInfo instance].areaId WithType:@"1" WithstartDate:nowMon WithendData:nextMon WithPage:@"1" Success:^(id obj, NSError *err) {
        _dataSource  = obj;
        [_tableV reloadData];
        //        NSLog(@"%@",_dataSource);
    }];
    
}
-(void)createUI{
//    添加头部viewview
    _topview= [[UIView alloc]initWithFrame:CGRectMake(0,64, SCREEN_WIDTH, SCREEN_HEIGHT/5)];
    _topview.backgroundColor  = [UIColor colorWithRed:0.25 green:0.44 blue:0.63 alpha:1];
//        _topview.backgroundColor  = [UIColor redColor];
    [self.view addSubview:_topview];
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/8, 0, _topview.bounds.size.height/9*4, _topview.bounds.size.height/9*4)];
    imageV.backgroundColor = [UIColor blueColor];
    imageV.image = [UIImage imageNamed:@"xic_launcher"];
    imageV.layer.cornerRadius =_topview.bounds.size.height/18*4;
    imageV.layer.masksToBounds = YES;
    [_topview addSubview:imageV];
    
    UILabel * titleLab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH/8 + _topview.bounds.size.height/2 , _topview.bounds.size.height/8, SCREEN_WIDTH -(SCREEN_WIDTH/8 + _topview.bounds.size.height/2), _topview.bounds.size.height/4)];
//    titleLab.backgroundColor = [UIColor grayColor];
    titleLab.text =@"青岛聚城网络科技有限公司";
    titleLab.textColor = [UIColor whiteColor];
    [_topview addSubview:titleLab];
    
    NSArray *nameArr = @[@"扫一扫",@"同步数据",@"一键提交"];
    NSArray *imageArr = @[@"device_ic_scan",@"device_ic_update",@"device_ic_submit"];
    for (int i = 0; i < 3; i ++ ) {
        
    UIButton *button  = [[UIButton alloc]initWithFrame:CGRectMake(20 + (SCREEN_WIDTH - 40)/3*i, _topview.bounds.size.height/2, (SCREEN_WIDTH - 40)/3, _topview.bounds.size.height/2)];
//    button.backgroundColor = [ UIColor colorWithRed:0.50 green:0.55 blue:0.55 alpha:1.0];
    UIImageView *sysIamgeV = [[UIImageView alloc]initWithFrame:CGRectMake(button.bounds.size.width / 2 - button.bounds.size.height/4, 0, button.bounds.size.height/2, button.bounds.size.height/2)];
//        sysIamgeV.backgroundColor = [UIColor greenColor];
    [sysIamgeV setImage:[UIImage imageNamed:imageArr[i]]];
    [button addSubview:sysIamgeV];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, button.bounds.size.height/2, button.bounds.size.width, button.bounds.size.height/2)];
    label.text = nameArr[i];
//        label.backgroundColor = [UIColor orangeColor];
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:14];
    label.textAlignment = NSTextAlignmentCenter;
    [button addSubview:label];
    button.tag = i+666;
    [button addTarget:self action:@selector(onButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [_topview addSubview:button];
    }
    
    for (int i = 0; i < 4; i ++) {
        
    }
    
    
}

-(void)createTableView{
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, 64 + SCREEN_HEIGHT/5, SCREEN_WIDTH, SCREEN_HEIGHT  - (64 + SCREEN_HEIGHT/5))];
    _tableV.backgroundColor  = [UIColor redColor];
    _tableV.delegate = self;
    _tableV.dataSource =self;
    _tableV.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.0];
    [self.view addSubview:_tableV];
    [_tableV setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
//    创建空值时候的提示label
    _nilLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, SCREEN_HEIGHT/2, SCREEN_WIDTH, 80)];
//    _nilLabel.text = @"本月没有待巡检设备";
    _nilLabel.textColor = [UIColor lightGrayColor];
    _nilLabel.font = [UIFont systemFontOfSize:25];
    _nilLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_nilLabel];
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    GCMEQUShouYeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[GCMEQUShouYeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    [cell setBackgroundColor:[UIColor colorWithRed:.93 green:.93 blue:.93 alpha:1]];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    //    cell.textLabel.textColor = [UIColor colorWithRed:0.39 green:0.39 blue:0.39 alpha:1];
    GCMEQUShouYeModel *listModel = _dataSource[indexPath.row];
    //NSLog(@"%@",listModel.contact);
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setSheBeiModel:listModel];
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 180;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GCMEQUShouYeModel *listModel = _dataSource[indexPath.row];
    GCMEQUErJiViewController * reciveVC = [[GCMEQUErJiViewController alloc]init];
    reciveVC.sbid = listModel.sbid;
    reciveVC.type = listModel.type;
    reciveVC.sbname = listModel.sbname;
    [self.navigationController pushViewController:reciveVC animated:NO ];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"设备计划";
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.backBarButtonItem = backItem;
}


-(void)onButtonClick:(UIButton *)button{

    if (button.tag == 666) {
        SubLBXScanViewController *vc = [SubLBXScanViewController new];
        [self.navigationController pushViewController:vc animated:YES];
        UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
        backItem.title = @"返回";
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        self.navigationItem.backBarButtonItem = backItem;
    }
    if (button.tag == 667) {
        if ([GCMCZHRequst isExistenceNetwork]) {
            //    日期
            NSString *timestr = [NSString stringWithFormat:@"%@",[NSDate date]];
            NSArray *arrayt1 = [timestr componentsSeparatedByString:@" "];
            NSArray *monArr = [arrayt1[0] componentsSeparatedByString:@"-"];
            NSString *nowMon = [NSString stringWithFormat:@"%@-%@-1", monArr[0],monArr[1]];
            [GCMSheBeiRequst postoutlineSheBeiDataWithaId:[GCMUserInfo instance].areaId WithstartDate:nowMon Success:^(id obj, NSError *err) {
                _outlinedataSource  =obj;
                NSLog(@"-------%@",_outlinedataSource);
                NSString *str = [NSString stringWithFormat:@"您有%ld条数据需要同步",_outlinedataSource.count];
                // 1.实例化alert:alertControllerWithTitle
                UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:str message:@"您确定要同步待操作设备？" preferredStyle:UIAlertControllerStyleAlert];
                [alertControl addAction:[UIAlertAction actionWithTitle:@"同步设备" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                    [LSProgressHUD showWithMessage:@"正在同步数据，请稍后"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self saveData];
                        [LSProgressHUD hide];
                        [ProgressHUD showSuccess:@"同步数据成功"];
                    });
                }]];
                [alertControl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
                [self presentViewController:alertControl animated:YES completion:nil];
            }];
            
            
        }else{
            [ProgressHUD showError:@"请在有网络的时候尝试"];
        }
        
    }
    if (button.tag == 668) {
        if ([GCMCZHRequst isExistenceNetwork]) {
            // 1.实例化alert:alertControllerWithTitle
            DBManage * manage = [DBManage defaultDBMessage];
            NSLog(@"1111%@",[manage alloperateSheBei]);
            NSMutableArray * mArr = [NSMutableArray arrayWithArray:[manage alloperateSheBei]];
            NSString *str = [NSString stringWithFormat:@"您有%ld条数据需要同步",mArr.count];
            UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:str message:@"您确定要上传离线操作的数据？" preferredStyle:UIAlertControllerStyleAlert];
            if (mArr.count == 0) {                
                [alertControl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            
            }else{
                [alertControl addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
                    [LSProgressHUD showWithMessage:@"正在上传数据，请稍后"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self uploadData];
                        [LSProgressHUD hide];
                        [ProgressHUD showSuccess:@"上传数据成功"];
                    });
                    
                    [self uploadData];
                }]];
                
                [alertControl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
            }
            
            [self presentViewController:alertControl animated:YES completion:nil];
            
        }else{
            [ProgressHUD showError:@"请在有网络的时候尝试"];
        }
        
    }
}

-(void)uploadData{
    //            取到所有的离线的操作数据
    DBManage * manage = [DBManage defaultDBMessage];
    NSLog(@"1111%@",[manage alloperateSheBei]);
    NSMutableArray * mArr = [NSMutableArray arrayWithArray:[manage alloperateSheBei]];
    for (GCMOUTLINECaoZuoModel *model in mArr) {
        int i = 0;
        NSDictionary *parameters= [[NSDictionary alloc]init];
        parameters  = [GCMCZHRequst dictionaryWithJsonString:model.operate];
        NSLog(@"444444%@",parameters);
        [GCMSheBeiRequst postSheBeiDataWithParmerts:parameters WithUrl:SHEBSUBPLAN_URL Success:^(id obj, NSError *err) {
            if ([obj valueForKey:@"success"]) {
                [manage deleteoperateSheBeiWithID:model.ID];
                NSLog(@"22222%@",[manage alloperateSheBei]);
            }else{
                [ProgressHUD showError:@"上传失败"];
            }
        }];
        i++;
    }
}
-(void)saveData{
    DBManage * manage = [DBManage defaultDBMessage];
    [manage deleteAllSheBei];
//    NSLog(@"----datasource---%@",_outlinedataSource);
    for (GCMEQUShouYeModel *model in _outlinedataSource) {
        GCMOUTLINESheBei *shebei  = [[GCMOUTLINESheBei alloc]init];
        shebei.sbname = model.sbname;
        shebei.type = model.type;
        shebei.sbid = model.sbid;
        shebei.zq = model.zq;
        shebei.days = model.days;
        shebei.xjrq = model.scxjrq;
        //把数据存到数据库
        DBManage * manage = [DBManage defaultDBMessage];
        [manage addSheBei:shebei];
    }
//    NSLog(@"888888%@",[manage allSheBei]);
}
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

//在页面消失的时候就让出现
- (void)viewWillDisappear:(BOOL)animated
{
    navBarHairlineImageView.hidden = NO;
    rigbutton.hidden = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
